package org.project.task.controller;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/image")
public class ImageUploadController {

    @PostMapping("/uploadImages")
    public ResponseEntity<?> uploadFiles(@RequestParam("pics") List<MultipartFile> files) {
        if (files == null || files.isEmpty()) {
            return ResponseEntity.badRequest().body("文件为空, 上传失败");
        }
        List<String> filePaths = new ArrayList<>();
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                continue;
            }
            try {
                String fileName = System.currentTimeMillis() + "-" + file.getOriginalFilename();
                String path = System.getProperty("user.dir");
                path += "/src/main/resources/static/images/";
                File dest = new File(path + fileName);
                file.transferTo(dest);
                filePaths.add("/images/" + fileName);
            } catch (IOException e) {
                e.printStackTrace();
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("上传失败");
            }
        }
        String result = String.join(";", filePaths);
        return ResponseEntity.ok(result);
    }

}